package com.example.nick.bodyapplication.recycler;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.nick.bodyapplication.R;

import java.util.ArrayList;

public class List2Activity extends AppCompatActivity {

    public static final String TAG = "list";
    RecyclerView recyclerView;
    LinearLayoutManager linearLayoutManager;
    PlayAdapter playAdapter;
    ArrayList<Integer> playListData = new ArrayList<>();

    TextView tvTitle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list2);

        initList();
    }

    private void initList() {
        recyclerView = findViewById(R.id.recyclerViewList);
        tvTitle = findViewById(R.id.tv_title);

        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        for (int i = 0; i < 9; i++) {
            playListData.add(i);
        }
        playAdapter = new PlayAdapter(R.layout.list_item, playListData);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addOnScrollListener(mOnScrollListener);
        recyclerView.setAdapter(playAdapter);

        playAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View v, int position) {
                Log.i("list", "list onItemClick pos:"+position);
                if (tvTitle.getVisibility() == View.VISIBLE) {
                    tvTitle.setVisibility(View.GONE);
                }

            }
        });

        playAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View v, int position) {
                Log.i("list", "list onItemChildClick pos:"+position);
                tvTitle.setVisibility(View.VISIBLE);
                tvTitle.setText("click:"+position);

                mIsClickToStop = true;
                mCurrentPlayArea = linearLayoutManager.findViewByPosition(position);
                tvTitle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.e(TAG, "tvTitle mCurrentActiveVideoItem:"+mCurrentActiveVideoItem);
                        Log.e("list", "tvTitle w:"+tvTitle.getWidth()+", h:"+tvTitle.getHeight());
                    }
                });
                Log.i("list", "mCurrentPlayArea w:"+mCurrentPlayArea.getWidth()+", h:"+mCurrentPlayArea.getHeight());
                mCurrentActiveVideoItem = position;
                mCanTriggerStop = true;

                //move container view
                startMoveFloatContainer(true);
            }
        });
    }

    private View mCurrentPlayArea;
    private int mCurrentActiveVideoItem = -1;
    private boolean mCanTriggerStop = true;
    /**
     * Stop video have two scenes
     * 1.click to stop current video and start a new video
     * 2.when video item is dismiss or ViewPager changed ? tab changed ? ...
     */
    private boolean mIsClickToStop;

    private float mOriginalHeight;

    private float mMoveDeltaY;

    private void startMoveFloatContainer(boolean click) {

        if (tvTitle.getVisibility() != View.VISIBLE) return;
        final float moveDelta;

        if (click) {
            Log.e(TAG, "startMoveFloatContainer > mFloatVideoContainer getTranslationY:" + tvTitle.getTranslationY());
            ViewAnimator.putOn(tvTitle).translationY(0);

            int[] playAreaPos = new int[2];
            int[] floatContainerPos = new int[2];
            mCurrentPlayArea.getLocationOnScreen(playAreaPos);
            tvTitle.getLocationOnScreen(floatContainerPos);
            mOriginalHeight = moveDelta = playAreaPos[1] - floatContainerPos[1];

            Log.e(TAG, "startMoveFloatContainer > mFloatVideoContainer playAreaPos[1]:" + playAreaPos[1] + " floatContainerPos[1]:" + floatContainerPos[1]);
        } else {
            moveDelta = mMoveDeltaY;
            Log.e(TAG, "ListView moveDelta :" + moveDelta + "");
        }

        float translationY = moveDelta + (!click ? mOriginalHeight : 0);

        Log.e(TAG, "startMoveFloatContainer > moveDelta:" + moveDelta + " before getTranslationY:" + tvTitle.getTranslationY()
                + " mOriginalHeight:" + mOriginalHeight + " translationY:" + translationY);

        ViewAnimator.putOn(tvTitle).translationY(translationY);

        Log.i(TAG, "startMoveFloatContainer < after getTranslationY:" + tvTitle.getTranslationY());
    }

    RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {

        int totalDy;

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            Log.e(TAG, "onScrollStateChanged state:" + newState);
            if (RecyclerView.SCROLL_STATE_IDLE == newState) {
                mOriginalHeight = tvTitle.getTranslationY();
                totalDy = 0;
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            /**
             * NOTE: RecyclerView will callback this method when {@link RecyclerViewFragment#onConfigurationChanged(Configuration)}
             * happened,so handle this special scene.
             */
//            if(mPlayerControlListener.isFullScreen()) return;

            //Calculate the total scroll distance of RecyclerView
            totalDy += dy;
            mMoveDeltaY = -totalDy;
            Log.e(TAG, "onScrolled scrollY:" + -totalDy);
            startMoveFloatContainer(false);

            if (mCurrentActiveVideoItem < linearLayoutManager.findFirstVisibleItemPosition()
                    || mCurrentActiveVideoItem > linearLayoutManager.findLastVisibleItemPosition()) {
                if (mCanTriggerStop) {
                    mCanTriggerStop = false;
                    stopPlaybackImmediately();
                }
            }
        }
    };

    public void stopPlaybackImmediately() {

        mIsClickToStop = false;

        if (mCurrentPlayArea != null) {
            mCurrentPlayArea.setClickable(true);
        }

        tvTitle.setVisibility(View.GONE);
//        if (mVideoPlayerManager != null) {
//            Log.e(TAG, "check play stopPlaybackImmediately");
//            tvTitle.setVisibility(View.INVISIBLE);
//            mVideoPlayerManager.stopAnyPlayback();
//        }
    }

}